# -*- coding: utf-8 -*-
from pathlib import Path
from urllib import request
from urllib import parse
import json
import re
base_url = "http://nanning.gongjiao.com"
lines_num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'w', 'x', 'y', 'z']

"""
初始化线路存储目录
"""
def init_lines():
    p = Path('./lines')
    if p.exists() == False:
        p.mkdir()
"""
下载html
"""
def download_html(url):
    req = request.Request(url)
    req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
    with request.urlopen(req) as f:
        data = f.read().decode("utf-8")
        return data
"""
下载首页
"""
def download_home():
    data = download_html(base_url)
    print(data)
    res = re.findall('<div class="gj01_item gj01_item_01">(.*?)</div>',data,re.S)
    if len(res)==1:
        data = res[0]
        res = re.findall('<a target="_blank" href="/lines_([1-9a-z]).html" >.*?</a>',data,re.S)
        print(res)
"""
下载线路号信息
"""
def download_and_save_line(num):
    url = base_url+"/lines_%s.html" % num
    print("url:%s" % url)
    data = download_html(url)
    with open('./lines/%s.html' % num, 'w', encoding="utf-8") as f:
        f.write(data)
"""
解析线路查询页
"""
def parse_line(num,data):
    res = re.findall('<div class="list">(.*?)</div>',data,re.S)
    if len(res)==1:
        data = res[0]
        res = re.findall('<a href="http://[0-9a-z]*?.gongjiao.com/xianlu_([0-9]*)">(.*?)</a>',data,re.S)
        if len(res)!=0:
            with open('lines.txt', 'a+', encoding="utf-8") as f:
                for item in res:
                    f.write("%s%s\t%s\t\n" % (num,item[0],item[1]))
"""
下载并解析线路查询页
"""
def download_and_parse_line(num):
    url = base_url+"/lines_%s.html" % num
    print("url:%s" % url)
    data = download_html(url)
    parse_line(num,data)

"""
解析线路
"""
def parse_xianlu(data):
    ress = []
    res = re.findall('<ul class="gj01_line_img JS-up clearfix">(.*?)</ul>',data,re.S)

    if len(res)!=0:
        data = res[0]
        res = re.findall('<a target="_blank" href="http://[0-9a-z]*?.gongjiao.com/zhandian_([0-9]*)"><i></i>(.*?)</a>',data,re.S)
        if len(res)!=0:
            return res
    return ress

"""
下载并解析线路详情
"""
def download_and_parse_xianlu(id):
    url = base_url+"/xianlu_%s" % id
    print("url:%s" % url)
    data = download_html(url)
    return parse_xianlu(data)

"""
地址转经纬度
"""
def address_to_location(address):
    ress = ""
    city = parse.quote("南宁")
    address = parse.quote(address)
    url = "https://restapi.amap.com/v3/geocode/geo?key=667dd97cc9ca502c88dee11bfdabf056&=city=%s&address=%s&output=JSON" % (city,address)
    res = download_html(url)
    data = json.loads(res)
    if data['status'] == '1':
        if len(data['geocodes'])!=0:
           ress = data['geocodes'][0]['location']
    return ress
if __name__== "__main__":
    # init_lines()
    # download_home()
    # for item in lines_num:
    #     download_and_parse_line(item)
    res = address_to_location("广西大学")
    print(res)
